package com.android.signhelper.model;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.os.Bundle;
import android.support.annotation.CheckResult;
import android.util.Log;

import com.android.signhelper.interfaces.MyCallback;
import com.android.signhelper.bean.SignInfo;
import com.android.signhelper.bean.Student;
import com.android.signhelper.db.MyDatabase;
import com.android.signhelper.http.SignClient;
import com.android.signhelper.jsonbean.detail.Detail;
import com.android.signhelper.jsonbean.login.Login;
import com.android.signhelper.jsonbean.sign.Sign;

import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.disposables.Disposables;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.internal.disposables.DisposableContainer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by ikata on 2018/11/14.
 */

public class MainModel {

    private MyDatabase myDatabase;
    private CompositeDisposable compositeDisposable;

    public CompositeDisposable getCompositeDisposable() {
        return compositeDisposable;
    }

    public MyDatabase getMyDatabase() {
        return myDatabase;
    }

    public MainModel()
    {
        myDatabase=new MyDatabase();
        compositeDisposable = new CompositeDisposable();
    }
    public void login(final String userName, final String password, final MyCallback callback)
    {
        final String params="{password:"+password+",userName:"+userName+"}";

        SignClient.getInstance().login(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Login>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(Login login) {
                        Log.d("jsonString", login.toString());
                        //数据缓存
                        if (login.getResult().getIsSuccess().equals("1")) {
                            Student student = new Student(userName, password);
                            student.setToken(login.getResult().getToken());
                            student.setName(login.getResult().getUserinfo().getUserZhname());
                            myDatabase.insertStudent(student);
                        }
                        Bundle bundle = new Bundle();
                        bundle.putParcelable("data", login);
                        callback.onSuccess(bundle);
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        Log.d("login-error", throwable.toString());
                        callback.onFailed(throwable.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void detail(final String token, final MyCallback callback)
    {
        final Disposable disposable=
        SignClient.getInstance().getDetail(token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Detail>() {
                    @Override
                    public void accept(Detail detail) throws Exception {
                        Log.d("jsonString", detail.toString());
                        //存储
                        //获取数据成功
                        if (detail.getStatus() == 1) {
                            String msg;
                            if (detail.getData() == null) {
                                msg = detail.getMessage();
                            } else {
                                if (detail.getData().getIsAvailable().equals("1")) {
                                    msg = "可签到(" + detail.getData().getStartTime() + "~" + detail.getData().getEndTime() + ")";
                                } else {
                                    msg = "不可签到";
                                }
                            }
                            //更新student
                            ContentValues values = new ContentValues();
                            values.put("message", msg);
                            myDatabase.updateStudent(myDatabase.getUserName(token), values);
                            //缓存signInfo
                            SignInfo signInfo = new SignInfo(Integer.valueOf(detail.getData().getIsAvailable())
                                    , detail.getData().getSignId()
                                    , detail.getData().getBleinfoList().get(0).getBleId()
                                    , detail.getData().getBleinfoList().get(0).getBleUuid());
                            //signInfo缓存成功在绑定对应的student
                            if (myDatabase.insertSignInfo(signInfo)) {
                                myDatabase.bindInfo(myDatabase.getUserName(token), signInfo.getDevUuid());
                            }
                        }
                        Bundle bundle = new Bundle();
                        bundle.putParcelable("data", detail);
                        callback.onSuccess(bundle);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.d("detail-error", throwable.getMessage() + throwable.getCause());
                        callback.onFailed(throwable.getMessage());
                    }
                });
        compositeDisposable.add(disposable);
    }

    @SuppressLint("CheckResult")
    public void sign(final String token, final Map<String,String> map, final MyCallback callback)
    {
        Disposable disposable=SignClient.getInstance().sign(token, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Sign>() {
                               @Override
                               public void accept(Sign sign) throws Exception {
                                   Log.d("jsonString", sign.toString());
                                   String msg;
                                   //数据获取正常
                                   if (sign.getStatus()==1){
                                       msg = sign.getData().getMessage();
                                   }else {
                                       msg = sign.getMessage();
                                   }
                                   //更新msg
                                   ContentValues values = new ContentValues();
                                   values.put("message",msg);
                                   myDatabase.updateStudent(myDatabase.getUserName(token),values);
                                   Bundle bundle = new Bundle();
                                   bundle.putParcelable("data", sign);
                                   callback.onSuccess(bundle);
                               }
                           }
                        , new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                Log.d("sign-error", throwable.getMessage()+throwable.getCause());
                                callback.onFailed(throwable.getMessage());
                            }
                        });
        compositeDisposable.add(disposable);
    }

    public Student queryData(String token)
    {
       return myDatabase.queryStudent(token);
    }

}
